package models

import (
	"strconv"

	"github.com/beego/beego/v2/client/orm"
)

// Store 门店模型
type Store struct {
	BaseModel
	Name          string  `orm:"size(100)" json:"name"`
	Logo          string  `orm:"size(255)" json:"logo"`
	Address       string  `orm:"size(255)" json:"address"`
	Latitude      float64 `orm:"digits(10);decimals(6)" json:"latitude"`
	Longitude     float64 `orm:"digits(10);decimals(6)" json:"longitude"`
	ContactPerson string  `orm:"size(50)" json:"contact_person"`
	Phone         string  `orm:"size(20)" json:"phone"`
	Description   string  `orm:"size(500)" json:"description"`
	BusinessHours string  `orm:"size(1024)" json:"business_hours"` // 营业时间，JSON格式存储
	Facilities    string  `orm:"size(500)" json:"facilities"`      // 设施，JSON格式存储
	Images        string  `orm:"size(255)" json:"images"`          // 门店图片，JSON格式存储
	Banner        string  `orm:"size(1024)" json:"banner"`         // 门店轮播图，JSON格式存储
	Notice        string  `orm:"type(text)" json:"notice"`           // 弹窗通知信息
	Status        int8    `orm:"default(1)" json:"status"`         // 1:正常, 0:禁用
	CityId        int64   `orm:"index" json:"city_id"`             // 所属城市ID
	VenueTypes    string  `orm:"size(500)" json:"venue_types"`     // 场地类型，JSON格式存储，例如: [1,2,3]
	SortOrder     int     `orm:"default(0)" json:"sort_order"`     // 排序
	IsHot         int8    `orm:"default(0)" json:"is_hot"`         // 是否热门，1:是，0:否
}

// TableName 设置表名
func (s *Store) TableName() string {
	return "ss_store"
}

// GetStoreById 根据ID获取门店信息
func GetStoreById(id int64) (*Store, error) {
	store := &Store{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(store)
	return store, err
}

// GetStoresByIds 根据ID列表获取门店信息
func GetStoresByIds(ids []int64) ([]*Store, error) {
	o := orm.NewOrm()
	var stores []*Store
	_, err := o.QueryTable(new(Store)).Filter("id__in", ids).Filter("is_deleted", 0).All(&stores)
	return stores, err
}

// GetStoreList 获取门店列表
func GetStoreList(page, pageSize int, filters map[string]interface{}) ([]*Store, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Store))

	// 应用过滤条件
	if franchiseId, ok := filters["franchise_id"].(int64); ok {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	if cityId, ok := filters["city_id"].(int64); ok {
		qs = qs.Filter("city_id", cityId)
	}

	// 增强搜索功能，支持名称和地址搜索
	if name, ok := filters["name"].(string); ok && name != "" {
		// 使用OR条件，匹配名称或地址
		cond := orm.NewCondition()
		cond = cond.Or("name__icontains", name).Or("address__icontains", name)
		qs = qs.SetCond(cond)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	if isHot, ok := filters["is_hot"].(int8); ok {
		qs = qs.Filter("is_hot", isHot)
	}

	// 场馆类型ID筛选 (VenueTypes是JSON数组格式)
	if venueTypeId, ok := filters["venue_type_id"].(int); ok && venueTypeId > 0 {
		// 由于是JSON数组，我们需要使用LIKE来模糊匹配
		// 对应的SQL类似于: WHERE venue_types LIKE '%,1,%' OR venue_types LIKE '[1,%' OR venue_types LIKE '%,1]' OR venue_types = '[1]'
		typeIDStr := strconv.Itoa(venueTypeId)
		condition := orm.NewCondition()
		condition = condition.Or("venue_types__contains", ","+typeIDStr+",")
		condition = condition.Or("venue_types__contains", "["+typeIDStr+",")
		condition = condition.Or("venue_types__contains", ","+typeIDStr+"]")
		condition = condition.Or("venue_types", "["+typeIDStr+"]")
		qs = qs.SetCond(condition)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var stores []*Store
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&stores)

	return stores, total, err
}

// CreateStore 创建门店
func CreateStore(store *Store) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(store)
	return id, err
}

// UpdateStore 更新门店信息
func UpdateStore(store *Store, fields ...string) error {
	o := orm.NewOrm()
	// 如果没有指定字段，则更新所有字段
	if len(fields) == 0 {
		_, err := o.Update(store)
		return err
	}
	// 否则只更新指定字段
	_, err := o.Update(store, fields...)
	return err
}

// DeleteStore 删除门店（软删除）
func DeleteStore(id int64) error {
	o := orm.NewOrm()
	store := &Store{BaseModel: BaseModel{Id: id}}
	if err := o.Read(store); err != nil {
		return err
	}

	store.IsDeleted = 1
	_, err := o.Update(store, "IsDeleted")
	return err
}

// GetStoresByFranchiseId 获取指定加盟商的门店列表
func GetStoresByFranchiseId(franchiseId int64) ([]*Store, error) {
	o := orm.NewOrm()
	var stores []*Store
	_, err := o.QueryTable(new(Store)).Filter("franchise_id", franchiseId).Filter("is_deleted", 0).OrderBy("sort_order", "-id").All(&stores)
	return stores, err
}

// GetStoreCount 获取门店总数
func GetStoreCount(franchiseId int64) (int64, error) {
	o := orm.NewOrm()
	var count int64

	// 构建查询条件
	whereClause := "is_deleted = 0"
	params := []interface{}{}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND franchise_id = ?"
		params = append(params, franchiseId)
	}

	// 执行查询
	err := o.Raw("SELECT COUNT(*) FROM ss_store WHERE "+whereClause, params...).QueryRow(&count)
	return count, err
}

// GetStoreVenues 获取门店场地列表
func GetStoreVenues(storeId int64) ([]*Venue, error) {
	o := orm.NewOrm()
	var venues []*Venue
	_, err := o.QueryTable(new(Venue)).Filter("store_id", storeId).Filter("is_deleted", 0).OrderBy("sort_order", "-id").All(&venues)
	return venues, err
}

// GetStoreVenuesByType 根据类型获取门店场地列表
func GetStoreVenuesByType(storeId int64, typeId int) ([]*Venue, error) {
	o := orm.NewOrm()
	var venues []*Venue
	qs := o.QueryTable(new(Venue)).Filter("store_id", storeId).Filter("is_deleted", 0)

	if typeId > 0 {
		if vt, _ := GetVenueTypeById(int64(typeId)); vt != nil {
			qs = qs.Filter("venue_type", vt.Name)
		}
	}

	_, err := qs.OrderBy("sort_order", "-id").All(&venues)
	return venues, err
}

// GetStoreByName 根据门店名称获取门店信息
func GetStoreByName(name string) (*Store, error) {
	if name == "" {
		return nil, orm.ErrNoRows
	}

	o := orm.NewOrm()
	store := &Store{}

	err := o.QueryTable(new(Store)).
		Filter("name", name).
		Filter("is_deleted", 0).
		One(store)

	return store, err
}

// GetStoreIdsByFranchiseId 获取指定加盟商的门店ID列表
func GetStoreIdsByFranchiseId(franchiseId int64) ([]int64, error) {
	o := orm.NewOrm()
	var storeIds []int64
	_, err := o.QueryTable(new(Store)).Filter("franchise_id", franchiseId).Filter("is_deleted", 0).OrderBy("sort_order", "-id").All(&storeIds)
	return storeIds, err
}
